package com.example.coffeeseller_2.model.helper.view_helper;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.coffeeseller_2.R;
import com.example.coffeeseller_2.model.beans.DealRecorder;
import com.example.coffeeseller_2.model.contentprovider.HardwareContance;
import com.example.coffeeseller_2.model.helper.MkCoffeeHelper;
import com.example.coffeeseller_2.model.listenner.OnMakeCoffeeProcessListenner;
import com.example.coffeeseller_2.utils.AssetUtil;
import com.example.coffeeseller_2.utils.DensityUtil;
import com.example.coffeeseller_2.utils.MyLog;
import com.example.coffeeseller_2.utils.Waiter;

import java.util.Timer;
import java.util.TimerTask;

import cof.ac.inter.ContainerConfig;
import cof.ac.inter.ContainerType;

/**
 * Created by WH on 2018/8/11.
 * 制作中动画
 */

public class MakingViewHelper implements OnMakeCoffeeProcessListenner {

    private static String TAG = "MakingViewHelper";
    private View view;
    private ImageView mMakeImg;
    private TextView mUsedTime;
    private ProgressBar mProgressBar;
    private LinearLayout mLeft;
    private ImageView mStep_clear, mStep_downcup, mStep_modou, mStep_niangzao,
            mStep_fuliao, mStep_zhuangbei, mStep_finish;
    private Context context;
    private Handler handler;
    private Timer countTimeTimer;
    private TimerTask countTimeTimerTask;

    private Thread mThread;
    private long mlTimerUnit = 100;
    private int mlCount = 0;
    private int totalSec = 0;
    private int yushu = 0;
    private int min = 0, sec = 0;


    private int MAX_MAKING_PROGRESS = 92;
    private int INIT_PROGRESS = 5;
    private int CONTAIN_MAKING_PROGRESS_TIME = 550;
    private int perProgressUnit;
    private boolean isMakingFinish = false;
    private boolean isProgressAnimStart = false;
    private boolean isMakingOrPowerDown = false;
    private boolean isMakingOrDownPowerUsed = false;
    private MkCoffeeHelper mkCoffeeHelper;
    private int curProgress;
    private int maxProgress;
    private boolean isStop = false;
    private boolean haveCoffeeBeanStep = false;

    public MakingViewHelper(Handler handler, Context context) {//, OnMakeResultListenner onMakeResultListenner
        this.handler = handler;
        this.context = context;
        view = LayoutInflater.from(context).inflate(R.layout.include_making, null, false);
        bindViews(view);
        initData();
    }

    private void bindViews(View view) {

        mMakeImg = (ImageView) view.findViewById(R.id.makeImg);
        mUsedTime = (TextView) view.findViewById(R.id.usedTime);
        mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        mStep_clear = (ImageView) view.findViewById(R.id.step_clear);
        mStep_downcup = (ImageView) view.findViewById(R.id.step_downcup);
        mStep_modou = (ImageView) view.findViewById(R.id.step_modou);
        mStep_niangzao = (ImageView) view.findViewById(R.id.step_niangzao);
        mStep_fuliao = (ImageView) view.findViewById(R.id.step_fuliao);
        mStep_zhuangbei = (ImageView) view.findViewById(R.id.step_zhuangbei);
        mStep_finish = (ImageView) view.findViewById(R.id.step_finish);
        changeFinishState(mStep_clear);
    }

    public void clear() {
        view = LayoutInflater.from(context).inflate(R.layout.include_making, null, false);
        bindViews(view);
        stopCountTimer();
        mThread = null;
        isMakingFinish = false;
        isProgressAnimStart = false;
        isMakingOrPowerDown = false;
        isMakingOrDownPowerUsed = false;
        isStop = true;
        mlCount = 0;
        curProgress = 0;
        totalSec = 0;
        yushu = 0;
        min = 0;
        sec = 0;
        handler.removeCallbacksAndMessages(null);
    }

    public View getView() {
        return view;
    }

    private void initData() {

        float progressBarWidth = context.getResources().getDimension(R.dimen.making_progress_bar_width);
        maxProgress = mProgressBar.getMax();
        perProgressUnit = (maxProgress / 6);
        int perProgressWidth = (DensityUtil.dp2px(context, progressBarWidth) / 6);
        Log.d(TAG, "perProgressUnit= " + perProgressUnit);
    }

    private void initTime() {
    /*
  * 便于查看步骤
  * */
        int waterTotal = 0;
        CONTAIN_MAKING_PROGRESS_TIME = 0;
        for (int i = 0; i < DealRecorder.getInstance().getContainerConfigs().size(); i++) {
            ContainerConfig containerConfig = DealRecorder.getInstance().getContainerConfigs().get(i);

            if (containerConfig.getContainer() == ContainerType.BEAN_CONTAINER) {
                haveCoffeeBeanStep = true;

                if (HardwareContance.BURST_BUBBLE == 2) { //技诺冲泡器额外增加15s

                    CONTAIN_MAKING_PROGRESS_TIME += 30 * 1000;
                    MyLog.d(TAG, "技诺冲泡器");
                }

                //    CONTAIN_MAKING_PROGRESS_TIME += 20 * 1000;
            }

            if (containerConfig.getWater_capacity() != 0) {//步骤出水
                waterTotal += containerConfig.getWater_capacity();
                if (containerConfig.getMaterial_time() == 0) {
                    CONTAIN_MAKING_PROGRESS_TIME += 5 * 1000;//机器运作5s

                } else {
                    CONTAIN_MAKING_PROGRESS_TIME += 5 * 1000;//机器运作5s
                    CONTAIN_MAKING_PROGRESS_TIME += containerConfig.getMaterial_time() * 10 + 10 * 1000;//每个步骤机器运作大概8s
                }

            } else {
                CONTAIN_MAKING_PROGRESS_TIME += containerConfig.getMaterial_time() * 10 + 10 * 1000;//每个步骤机器运作大概8s
            }
            MyLog.d(TAG, "getContainer=" + containerConfig.getContainer());
            MyLog.d(TAG, "getWater_capacity=" + containerConfig.getWater_capacity());
            MyLog.d(TAG, "getMaterial_time=" + containerConfig.getMaterial_time());
            MyLog.d(TAG, "getWater_type=" + containerConfig.getWater_type());
            MyLog.d(TAG, "getContainer_id=" + containerConfig.getContainer_id());
            MyLog.d(TAG, "getRotate_speed=" + containerConfig.getRotate_speed());
            MyLog.d(TAG, "getStir_speed=" + containerConfig.getStir_speed());
            MyLog.d(TAG, "getWater_interval=" + containerConfig.getWater_interval());
        }
        CONTAIN_MAKING_PROGRESS_TIME += waterTotal * 10 * 10 / 10;

        //    CONTAIN_MAKING_PROGRESS_TIME += 30 * 1000;
        CONTAIN_MAKING_PROGRESS_TIME += 20 * 1000; //落杯过程中的10s

        MyLog.d(TAG, "CONTAIN_MAKING_PROGRESS_TIME= " + CONTAIN_MAKING_PROGRESS_TIME);
    }

    private void updateProgressAnim() {

        isProgressAnimStart = true;
        if (isMakingFinish) {

            Log.d(TAG, "isMakingFinish=  " + isMakingFinish);
            setProgress(mProgressBar.getMax());
            if (mThread != null) {
                mThread = null;
            }
            return;
        }

        if (mThread != null) {
            return;
        }

        if (mThread == null) {
            mThread = new Thread(new Runnable() {
                @Override
                public void run() {

                    int waitTime = CONTAIN_MAKING_PROGRESS_TIME / MAX_MAKING_PROGRESS;
                    int index = perProgressUnit;
                    if (!haveCoffeeBeanStep) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                setProgress(3 * perProgressUnit);
                            }
                        });
                        index = 3 * perProgressUnit;
                        waitTime = (CONTAIN_MAKING_PROGRESS_TIME - 2 * perProgressUnit * waitTime) / MAX_MAKING_PROGRESS;

                    }

                    for (int i = index; i <= MAX_MAKING_PROGRESS; i++) {

                      /*  //第一次落粉或制作,用于结束落杯状态
                        if (isMakingOrPowerDown && !isMakingOrDownPowerUsed) {
                            if (i < 2 * perProgressUnit) {
                                i = 2 * perProgressUnit;
                            }
                            isMakingOrDownPowerUsed = true;
                            waitTime = (CONTAIN_MAKING_PROGRESS_TIME -  perProgressUnit * waitTime) / MAX_MAKING_PROGRESS;

                        }*/

                      /*  //如果没有磨豆步骤,且已经结束落杯状态
                        if (!haveCoffeeBeanStep) {//!haveCoffeeBeanStep && isMakingOrDownPowerUsed
                            if (i < 3 * perProgressUnit) {
                                i = perProgressUnit * 3;
                                waitTime = (CONTAIN_MAKING_PROGRESS_TIME - 2 * perProgressUnit * waitTime) / MAX_MAKING_PROGRESS;
                            }
                        }*/

                        if (!isMakingFinish) {
                            final int finalI = i;
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    setProgress(finalI);
                                }
                            });
                            Waiter.doWait(waitTime);
                        } else {
                            break;
                        }
                    }
                    if (isMakingFinish)

                    {
                        mThread = null;
                    }
                }
            });
            mThread.start();
        }
    }

    private void setProgress(int progress) {
        int MAX_PROGRESS = 100;
        curProgress = progress;
        mProgressBar.setProgress(progress);
        if (progress < perProgressUnit) {
            changeFinishState(mStep_clear);
            return;
        }
        if (progress >= perProgressUnit && progress < 2 * perProgressUnit) {

            changeFinishState(mStep_clear);
            changeFinishState(mStep_downcup);
            return;
        }
        if (progress >= 2 * perProgressUnit && progress < 3 * perProgressUnit) {

            changeFinishState(mStep_clear);
            changeFinishState(mStep_downcup);
            changeFinishState(mStep_modou);
            return;
        }

        if (progress >= 3 * perProgressUnit && progress < 4 * perProgressUnit) {

            changeFinishState(mStep_clear);
            changeFinishState(mStep_downcup);
            changeFinishState(mStep_modou);
            changeFinishState(mStep_niangzao);
            return;
        }

        if (progress >= 4 * perProgressUnit && progress < 5 * perProgressUnit) {

            changeFinishState(mStep_clear);
            changeFinishState(mStep_downcup);
            changeFinishState(mStep_modou);
            changeFinishState(mStep_niangzao);
            changeFinishState(mStep_fuliao);

            return;
        }


        if (progress >= 5 * perProgressUnit && progress < MAX_PROGRESS) {

            changeFinishState(mStep_clear);
            changeFinishState(mStep_downcup);
            changeFinishState(mStep_modou);
            changeFinishState(mStep_niangzao);
            changeFinishState(mStep_fuliao);
            changeFinishState(mStep_zhuangbei);
            return;
        }

        if (progress == mProgressBar.getMax()) {

            changeFinishState(mStep_clear);
            changeFinishState(mStep_downcup);
            changeFinishState(mStep_modou);
            changeFinishState(mStep_niangzao);
            changeFinishState(mStep_fuliao);
            changeFinishState(mStep_zhuangbei);
            changeFinishState(mStep_finish);
            return;
        }

    }

    /*
    * 修改已完成图标
    * */
    private void changeFinishState(final ImageView view) {

        handler.post(new Runnable() {
            @Override
            public void run() {
                view.setImageResource(R.mipmap.make_coffee_finish);

            }
        });
    }

    public void setMkCoffeeHelper(MkCoffeeHelper mkCoffeeHelper) {
        this.mkCoffeeHelper = mkCoffeeHelper;
        mkCoffeeHelper.setMkProcessListenner(this);
    }

    public void countTime() {

        Log.d(TAG, "countTime()");
        if (countTimeTimer != null || countTimeTimerTask != null) {
            return;
        }
        if (null == countTimeTimer) {
            if (null == countTimeTimerTask) {
                countTimeTimerTask = new TimerTask() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                mlCount++;
                                totalSec = 0;
                                // 100 millisecond
                                totalSec = (int) (mlCount / (1000 / mlTimerUnit));
                                yushu = (int) (mlCount % (1000 / mlTimerUnit));
                                // Set time display
                                min = (totalSec / 60);
                                sec = (totalSec % 60);
                                try {
                                    // 100 millisecond
                                    mUsedTime.setText(String.format("%1$02d:%2$02d:%3$d", min, sec, yushu));
                                } catch (Exception e) {
                                    mUsedTime.setText("" + min + ":" + sec + ":" + yushu);
                                    e.printStackTrace();
                                    Log.e("MyTimer onCreate", "Format string error.");
                                }
                            }
                        });
                    }

                };
            }
            countTimeTimer = new Timer(true);
            countTimeTimer.schedule(countTimeTimerTask, mlTimerUnit, mlTimerUnit);
        }
    }


    public void stopCountTimer() {

        if (countTimeTimer != null) {
            countTimeTimer.cancel();
            countTimeTimer = null;
            countTimeTimerTask = null;
        }
    }

    public OnMakeCoffeeProcessListenner getListenner() {
        return this;
    }

    public void startAnim() {
        AnimTask task = new AnimTask();
        task.execute();
    }


    class AnimTask extends AsyncTask<Void, Integer, String> {
        private String pathName = "";
        private int count = 0;

        @Override
        protected String doInBackground(Void... params) {
            while (!isStop) {
                Log.d(TAG, "curProgress= " + curProgress);

                if (curProgress < perProgressUnit) {
                    pathName = "clear";
                    if (count > 20) {
                        count = 0;
                    }
                } else if (curProgress >= perProgressUnit && curProgress < perProgressUnit * 2) {
                    pathName = "downcup";
                    if (count > 25) {
                        count = 0;
                    }
                } else if (curProgress >= perProgressUnit * 2 && curProgress < perProgressUnit * 3) {
                    pathName = "modou";
                    if (count > 80) {
                        count = 0;
                    }
                } else if (curProgress >= perProgressUnit * 3 && curProgress < perProgressUnit * 4) {
                    pathName = "liangzao";
                    if (count > 25) {
                        count = 0;
                    }
                } else if (curProgress >= perProgressUnit * 4 && curProgress < perProgressUnit * 5) {
                    pathName = "fuliao";
                    if (count > 23) {
                        count = 0;
                    }
                } else if (curProgress >= perProgressUnit * 5 && curProgress < maxProgress) {
                    pathName = "zhuangbei";
                    if (count > 50) {
                        count = 0;
                    }
                } else {
                    pathName = "finish";
                    if (count > 119) {
                        count = 0;
                    }
                }
                publishProgress(count);
                Waiter.doWait(100);
                count++;
            }
            return "";
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            String countName = "";
            if (count < 10) {
                countName = "_00" + count;
            } else if (count >= 10 && count < 100) {
                countName = "_0" + count;
            } else if (count >= 100) {
                countName = "_" + count;
            }
              /*  TradeAnimManager.startMakingAnim(context, mMakeImg, pathName + countName);*/
               /* Glide.with(context)
                        .load(AssetUtil.PATH_HEAD + pathName + countName + ".png")
                        .into(mMakeImg);*/

            mMakeImg.setImageBitmap(AssetUtil.getAssetsBitmap(context, pathName + countName + ".png"));

        }

    }

    @Override
    public void init() {
        initTime();
        countTime();
        isStop = false;
        startAnim();

        for (int i = 0; i < perProgressUnit - 2; i++) {
            if (mProgressBar.getProgress() >= perProgressUnit) {
                break;
            }
            setProgress(i);
            Waiter.doWait(100 + i * 10);
        }
        Log.d(TAG, "init");

    }

    private void setStop(final boolean stop) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                isStop = stop;
            }
        }, 4000);
    }

    @Override
    public void downCup() {

        handler.post(new Runnable() {
            @Override
            public void run() {
                changeFinishState(mStep_downcup);
                setProgress(perProgressUnit);

                /*for (int i = perProgressUnit; i < 2 * perProgressUnit-5; i++) {
                    if (mProgressBar.getProgress() >= 2 * perProgressUnit) {
                        break;
                    }
                    setProgress(i);
                    Log.d(TAG, "init --" + i);
                    Waiter.doWait(300);

                }*/
                if (!isProgressAnimStart) {
                    updateProgressAnim();
                }
                Log.d(TAG, "downCup");
            }
        });
    }

    @Override
    public void downPower() {
        if (!isProgressAnimStart) {
            updateProgressAnim();
        }
        isMakingOrPowerDown = true;
        Log.d(TAG, "downPower");
    }

    @Override
    public void making() {
        if (!isProgressAnimStart) {
            updateProgressAnim();
        }
        Log.d(TAG, "making");
        isMakingOrPowerDown = true;
    }

    @Override
    public void finish() {

        isMakingFinish = true;
        updateProgressAnim();
        stopCountTimer();

        setStop(true);
      /*  if (onMakeResultListenner != null) {
            onMakeResultListenner.finish();
        }*/
        Log.d(TAG, "finish");

    }

    @Override
    public void failed() {

        if (mThread != null) {
            mThread = null;
        }
        stopCountTimer();
        setStop(true);
       /* if (onMakeResultListenner != null) {
            onMakeResultListenner.failed();
        }*/
    }
}
